from alipay import AliPay
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from django.conf import settings
from rest_framework.response import Response

from orders.models import OrderInfo
from pays.models import Payment


class AlipayView(APIView):
    def get(self,request,order_id):

        #1,准备公钥私钥
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH


        #2,创建alipy对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path = app_private_key_path,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=alipay_public_key_path,
            sign_type="RSA2", # RSA 或者 RSA2
            debug = False  # 默认False
        )


        #3,生成字符订单编号
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=9999,
            subject="国际美多商城订单",
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )

        #4,返回支付页面
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({"alipay_url":alipay_url})

class AlipayOrderStatusView(APIView):
    def put(self,request):
        #1,获取参数
        data = request.query_params.dict()
        signature = data.pop("sign")

        #2,校验参数
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path = app_private_key_path,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=alipay_public_key_path,
            sign_type="RSA2", # RSA 或者 RSA2
            debug = False  # 默认False
        )

        success = alipay.verify(data, signature)

        if not success:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,数据入库
        #3.1 创建payment对象
        order_id = data.get("out_trade_no")
        trade_id = data.get("trade_no")

        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_id
        )

        #3.2 修改订单信息状态
        OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

        #4,返回响应
        return Response({"trade_id":trade_id})

